package middleware

import (
	"gin-jwt-test/model"
	jwt "github.com/appleboy/gin-jwt/v2"
	"github.com/gin-gonic/gin"
	"log"
	"time"
)

// 唯一标识符
var identityKey = "-xtsci-"

func Auth() *jwt.GinJWTMiddleware {
	auth, err := jwt.New(&jwt.GinJWTMiddleware{
		Realm:       "dff919091a864d8a",
		Key:         []byte("xtsci"),
		Timeout:     time.Hour,
		MaxRefresh:  time.Hour,
		IdentityKey: identityKey,
		Authenticator: func(c *gin.Context) (interface{}, error) {
			// 登录名
			username := c.DefaultQuery("username", "")
			password := c.DefaultQuery("password", "")
			log.Println(username, password)
			// 如果是错误的话
			if username == "" || password == "" {
				return jwt.ErrFailedAuthentication, nil
			}
			um := model.User{}
			result, err := um.Query(username)

			if err != nil {
				log.Fatalln(err)
			} else {
				return result, nil
			}
			return jwt.ErrFailedAuthentication, nil
		},
		// 这里的问题
		PayloadFunc: func(data interface{}) jwt.MapClaims {
			if v, ok := data.(model.User); ok {
				log.Println("uuid",v.UUID)
				return jwt.MapClaims{
					"uuid":      v.UUID,
					"salt":      v.Salt,
					"username":  v.Username,
					identityKey: v.Username,
				}
			}
			return jwt.MapClaims{}
		},
		// 这里需要解决，还差最后一步

		IdentityHandler: func(context *gin.Context) interface{} {
			c := jwt.ExtractClaims(context)
			return c
		},
		Authorizator: func(data interface{}, c *gin.Context) bool {
			log.Println("Authorizator ->",data)
			return true
		},
		TokenLookup:   "header: Authorization, query: token, cookie: jwt",
		TokenHeadName: "Bearer",
		TimeFunc:      time.Now,
	})

	if err != nil {
		log.Fatal(err)
	}
	return auth
}
